package Server

import (
	"fmt"

	"github.com/TarsCloud/TarsGo/tars"
	"github.com/TarsCloud/TarsGo/tars/util/conf"
	"github.com/wzh200x/cacheServer/cache"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/cacheServerProtocol" // 导入缓存服务器协议包
)

type CacheServer struct {
	CacheManager *cache.CacheManager
}

func (ca *CacheServer) Init(comm *tars.Communicator, sConf *conf.Conf) error {
	// 初始化缓存管理器
	ca.CacheManager.Init(sConf)
	// 初始化tars
	ca.RegisterTarsObj()

	// 测试redis
	err := ca.CacheManager.RedisCache.Set("test", "test", 0)
	if err != nil {
		tars.GetLogger("").Errorf("redis set test error: %v", err)
	} else {
		tars.GetLogger("").Infof("redis set test success")
	}

	return nil
}

func (ca *CacheServer) InitFinish() error {
	return nil
}

func (ca *CacheServer) Info() string {
	return fmt.Sprintf(`server :%s version :%s`, "cacheServer", "0.0.1")
}

func (ca *CacheServer) Name() string {
	return "cacheServer"
}

func (ca *CacheServer) Stop() error {
	return nil
}

func (ca *CacheServer) RegisterTarsObj() {
	// Get server config
	cfg := tars.GetServerConfig()
	// New servant imp
	imp := new(cacheServerOperateImp)
	// 初始化servant
	err := imp.Init()
	if err != nil {
		tars.GetLogger("").Errorf("初始化cacheServerOperateImp失败: %v", err)
	}

	app := new(cacheServerProtocol.CacheServer)
	// Register Servant
	app.AddServantWithContext(imp, cfg.App+"."+cfg.Server+".CacheServerOperateObj")
}

func NewServer() *CacheServer {
	gs := &CacheServer{
		CacheManager: cache.NewCacheManager(),
	}
	return gs
}

var ServerApp *CacheServer = NewServer()
